package lv.solcraft.replication.client.boot;

import lv.solcraft.replication.client.logging.ClientLogger;

import org.springframework.beans.factory.config.PropertyPlaceholderConfigurer;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Client {

    private final ClassPathXmlApplicationContext applicationContext;
    private final ClientBootConfig config;

    public Client(ClientBootConfig config) throws Exception {
        this.config = config;
        config.validate();
        applicationContext = new ClassPathXmlApplicationContext(new String[] { "applicationContext-client.xml" });
        PropertyPlaceholderConfigurer cfg = new PropertyPlaceholderConfigurer();
        cfg.setProperties(config.asProperties());
        applicationContext.addBeanFactoryPostProcessor(cfg);
        applicationContext.refresh();
        // set configuration
        ClientBootConfig configBean = (ClientBootConfig) applicationContext.getBean("config");
        configBean.copyFrom(config);
        // force to create beans (by default they have lazy-init)
        applicationContext.getBean("scheduler");
        ClientLogger logger = (ClientLogger) applicationContext.getBean("logger");
        logger.infoLocal("\n\n------- STARTED -------\n");
    }

    public void stop() throws Exception {
        if (applicationContext != null)
            applicationContext.close();
    }

    public ClientBootConfig getConfig() {
        return config;
    }
}
